package com.ruoyi.system.controller;

import java.util.List;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysDeptTj;
import com.ruoyi.system.utils.Base64Util;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 商铺信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取商铺列表
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            dept.setAppId(user.getAppId());
        }
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    @GetMapping("/listTj")
    public AjaxResult listTj(SysDept dept)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            dept.setAppId(user.getAppId());
        }
        List<SysDeptTj> depts = deptService.selectShopTjList(dept);
        return success(depts);
    }

    @GetMapping("/listTjPay")
    public AjaxResult listTjPay(SysDept dept)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            dept.setAppId(user.getAppId());
        }
        List<SysDeptTj> depts = deptService.selectShopTjPayList(dept);
        return success(depts);
    }

    /**
     * 查询商铺列表（排除节点）
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据商铺编号获取详细信息
     */
    @RequiresPermissions("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增商铺
     */
    @RequiresPermissions("system:dept:add")
    @Log(title = "商铺管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("新增商铺'" + dept.getDeptName() + "'失败，商铺名称已存在");
        }
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        dept.setCreateBy(SecurityUtils.getUserId());
        if (!SysUser.isAdmin(user.getUserId())) {
            if (Base64Util.hasYwType(user.getYwType(), "1")) {
                dept.setAppId(user.getAppIdm());
            } else if (Base64Util.hasYwType(user.getYwType(), "2")) {
                dept.setAppId(user.getAppIdf());
            } else if (Base64Util.hasYwType(user.getYwType(), "3")) {
                dept.setAppId(user.getAppId());
            }
        }
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改商铺
     */
    @RequiresPermissions("system:dept:edit")
    @Log(title = "商铺管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("修改商铺'" + dept.getDeptName() + "'失败，商铺名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改商铺'" + dept.getDeptName() + "'失败，上级商铺不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该商铺包含未停用的子商铺！");
        }
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        dept.setUpdateBy(SecurityUtils.getUserId());
        if (!SysUser.isAdmin(user.getUserId())) {
            if (Base64Util.hasYwType(user.getYwType(), "1")) {
                dept.setAppId(user.getAppIdm());
            } else if (Base64Util.hasYwType(user.getYwType(), "2")) {
                dept.setAppId(user.getAppIdf());
            } else if (Base64Util.hasYwType(user.getYwType(), "3")) {
                dept.setAppId(user.getAppId());
            }
        }
        return toAjax(deptService.updateDept(dept));
    }

    @PutMapping("/pic")
    public R<Integer> updateDeptPic(@RequestBody SysDept dept)
    {
        dept.setUpdateBy(SecurityUtils.getUserId());
        return R.ok(deptService.updateDept(dept));
    }

    /**
     * 删除商铺
     */
    @RequiresPermissions("system:dept:remove")
    @Log(title = "商铺管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return warn("存在下级商铺,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return warn("商铺存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @RequiresPermissions("system:dept:editaddress")
    @Log(title = "商铺管理", businessType = BusinessType.UPDATE)
    @PutMapping("/address")
    public AjaxResult editaddress(@RequestBody SysDept dept)
    {
        return toAjax(deptService.updateDeptAdress(dept));
    }

    /**
     * 获取学校下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            dept.setAppId(user.getAppId());
        }
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色学校列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        SysDept dept = new SysDept();
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            dept.setAppId(user.getAppId());
        }
        List<SysDept> depts = deptService.selectDeptList(dept);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }
}
